﻿using MQTTnet.Server;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Linq;
using Z.EntityFramework.Plus;
using Masuit.Tools.Security;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using adb.excel;
using System.IO;
using Masuit.Tools;
using Microsoft.Net.Http.Headers;
using adb;
using System;
using Microsoft.Extensions.Caching.Memory;

namespace SensorCollection
{

    public class ValueFloatJsonModel
    {
        /// <summary>
        /// 警告值
        /// </summary>
        public decimal value { get; set; }
    }

    /// <summary>
    /// 发送浮点数据
    /// </summary>
    public class ControlFloat : IDataDealwith
    {
        private MqttServer mqttServer;
        private DbContextOptionsBuilder<DeviceDbContext> optionsBuilder;
        private DbContextOptionsBuilder<MyDbContext> MyOptionsBuilder;
        public ControlFloat(MqttServer mqttServer, DbContextOptionsBuilder<DeviceDbContext> optionsBuilde, DbContextOptionsBuilder<MyDbContext> MyOptionsBuilder)
        {
            this.mqttServer = mqttServer;
            this.optionsBuilder = optionsBuilde;
            this.MyOptionsBuilder = MyOptionsBuilder;
        }

        public long keyId => 820096;

        public object JsonToModel(string json, string deviceSN = null)
        {
            return System.Text.Json.JsonSerializer.Deserialize<ValueFloatJsonModel>(json);
        }

        public async Task ReactData(object data, string Topic, string deviceSN = null)
        {
            try
            {
                ValueFloatJsonModel obj = data as ValueFloatJsonModel;
                if (data == null) return;
                if (Topic.IsNullOrEmpty()) return;
                using (var db = new DeviceDbContext(this.optionsBuilder.Options))
                {
                    await db.tControlData.AddAsync(new tControlData
                    {
                        addTime = DateTime.Now,
                        deviceData = obj.value,
                        Topic = Topic
                    });
                    await db.SaveChangesAsync();
                }
            }
            catch (Exception ex) { 
                Console.WriteLine("tControlData:" + ex);
            }
        }

    }
}
